// pages/news-list/news-list.js
var common = require("../../utils/timestamp.js");
const throttle = require('../../utils/throttle.js')
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: '',
    inputVal: "", //input框内值
    input_value: "", //value值
    listarr: [], //创建数组
    SearchText: '取消', //按钮变动值
    keydown_number: 0, //检测input框内是否有内容
    hostarr: [], //热门搜索接收请求存储数组  
    name_focus: true, //获取焦点
    searchList: [],
    valueTrans: "", //传递过来的value值  
    currentPage: 1,
    requestendShow: false, //数据上拉加载完显示
    substrTime: [], //转换后的时间
    updateEnd: false, //控制底部加载状态
    dateCurrent3: -1,
    lastPageadd: [],
    searchShow: false,
    nodataImgShow: true
  },

  // 输入框监听
  bindInputValue: function(e) {
    var that = this;
    if (e.detail.cursor == 0) {
      that.setData({
        searchShow: false
      })
    } else {
      that.setData({
        searchShow: true
      })
    }
  },

  bindchangeValue: function() {
    return false
  },
  // 跳转详情页
  toNewsDetail: throttle.throttle(function(e) {
    var that = this;
    console.log(e.currentTarget.dataset);
    let $index = e.currentTarget.dataset.index 
    let article_id = e.currentTarget.id;
    // let shareImgSrc = e.currentTarget.dataset.imgsrc  //列表所携带的图片 分享需求时使用
    // console.log(article_id)
    that.setData({
      dateCurrent3: e.currentTarget.dataset.index
    })
    // 截取字符串中的数字 转换文章id格式
    console.log(e.currentTarget.id)
    let num = e.currentTarget.id.replace(/[^0-9]/ig, "");
    console.log(num);
    wx.navigateTo({
      url: '../news-detail/news-detail?article_id=' + num + '&page=' + 0, //传递文章id
    })
  }, 1000),
  // 失去焦点
  inputvalue2: function(e) {
    // console.log(e.detail.value)
    this.setData({
      inputVal: e.detail.value,
      nodataImgShow: true
    })
    if (e.detail.cursor != 0) {
      this.setData({
        SearchText: "搜索",
        keydown_number: 1,
        input_value: e.detail.value
      })
    } else {
      this.setData({
        SearchText: "取消",
        keydown_number: 0
      })
    }
    return false
  },
  // 列表搜索
  search2: throttle.throttle(function(e) {
    var that = this;
    if (that.data.input_value !== '') {
      var jsonData = {
        "data": {
          page: that.data.currentPage,
          keyword: that.data.input_value,
        },
        "memToken": "",
        "timestamp": "1"
      }
      wx.getStorage({
        key: 'list_arr',
        success: function(res) {
          console.log(res.data + '.......获取上一页历史记录')
          if (that.data.input_value !== '') {
            let arrnum = res.data.indexOf(that.data.input_value);
            if (arrnum < 0) { //<0不存在  
              res.data.unshift(that.data.input_value)

            } else { //否则存在
              res.data.splice(arrnum, 1)
              res.data.unshift(that.data.input_value)
            }
          }
          wx.setStorage({
            key: 'newVales',
            data: that.data.input_value,
          })
          console.log(res.data)
          // console.log(that.data.input_value)
          wx.setStorage({
            key: "list_arr",
            data: res.data
          })
        },
      })
      // 解析： http://www.cn-healthcare.com/api/search/搜索条件/页码（1开始）/0
      wx.request({
        url: 'https://www.cn-healthcare.com/freezingapi/api/article/rebangSearch',
        method: 'post',
        dataType: 'json',
        data: JSON.stringify(jsonData),
        header: {
          "Content-Type": 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          if (res.data.response.docs.length == 0) {
            that.setData({
              nodataImgShow: false
            })
          } else {
            console.log(res.data.response.docs)
            for (var i = 0; i < res.data.response.docs.length; i++) {
              // console.log(res.data.response.docs[i].pubdate.substring(0, 10))
              res.data.response.docs[i].pubdate = res.data.response.docs[i].pubdate.substring(0, 10)
              res.data.response.docs[i].pubdate = common.timeChangeover(res.data.response.docs[i].pubdate)
            }
          }
          that.setData({
            searchList: res.data.response.docs
          })

        }
      })
      that.setData({
        searchShow: false
      })

    }
  }, 1000),

  // 返回搜索页
  searchRemve: function(options) {
    wx.setStorage({
      key: 'newVales',
      data: options.valueTrans,
    })
    wx.navigateTo({
      url: '../search/search',
    })
  },
  //搜索方法
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let isIphoneX = app.globalData.isIphoneX;
    if (isIphoneX) {
      this.setData({
        isIphoneX: isIphoneX
      })
    }

    console.log(options.valueTrans)
    console.log(typeof(JSON.parse(options.searchList)))
    wx.setStorage({
      key: 'newVales',
      data: options.valueTrans,
    })
    if (typeof(JSON.parse(options.searchList)) == 'object') {
      this.setData({
        searchList: JSON.parse(options.searchList),
        input_value: options.valueTrans,
        name_focus: false
      })
    } else {
    }
    for (var i = 0; i < this.data.searchList.length; i++) {
      // console.log(this.data.searchList[i].pubdate.substring(0, 10))
      this.data.searchList[i].pubdate = this.data.searchList[i].pubdate.substring(0, 10)
      this.data.searchList[i].pubdate = common.timeChangeover(this.data.searchList[i].pubdate)
      this.setData({
        searchList: this.data.searchList,
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  // * 页面上拉触底事件的处理函数
  //  */
  onReachBottom: function() {
    var that = this;
    // 页数+1 每次上拉触底页数+1
    var page = that.data.currentPage + 1;
    this.setData({
      currentPage: page
    })
    var jsonData = {
      "data": {
        page: that.data.currentPage,
        keyword: that.data.input_value,
      },
      "memToken": "",
      "timestamp": "1"
    }
    wx.request({
      url: 'https://www.cn-healthcare.com/freezingapi/api/article/rebangSearch',
      method: 'post',
      dataType: 'json',
      data: JSON.stringify(jsonData),
      header: {
        "Content-Type": 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res.data.response.docs);
        var update_list = that.data.searchList;
        console.log(update_list)
        for (var i = 0; i < res.data.response.docs.length; i++) {
          update_list.push(res.data.response.docs[i]);
          // console.log(res.data.response.docs[i].pubdate.substring(0, 10))
          res.data.response.docs[i].pubdate = res.data.response.docs[i].pubdate.substring(0, 10)
          res.data.response.docs[i].pubdate = common.timeChangeover(res.data.response.docs[i].pubdate)
        }
        // 赋值数据
        that.setData({
          searchList: that.data.searchList
        })
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var that = this;
    if (res.from === 'button') {
      console.log("来自页面内转发按钮");
      console.log(res.target);
    } else {
      console.log("来自右上角转发菜单")
      let shareImg = that.data.head_img;
      let code = wx.getStorageSync('my_code');
      return {
        title: '健康界',
        imageUrl: '../img/shareimg.jpg',
        path: "/pages/news-list/news-list",
        success: function(res) {
          console.log("转发成功");
        },
        fail: function(res) {
          console.log("转发失败")
        }
      }
    }
  }
})